package cn.schoolwow.workflow.test.module.oa.loan.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.check.instance.CheckInstance;
import cn.schoolwow.workflow.QuickWorkFlow;
import cn.schoolwow.workflow.domain.instance.StartWorkFlowRequest;
import cn.schoolwow.workflow.domain.instance.WorkFlowInstanceStatus;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.test.module.analyzeWorkReport.audit.single.common.PrintWorkFlowInstanceHistoryFlow;
import com.alibaba.fastjson.JSONObject;

public class LoanAuditCommonFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        startWorkFlow(flowContext);
        checkStatus(flowContext);
    }

    @Override
    public String name() {
        return "贷款审批公共流程";
    }

    private void startWorkFlow(FlowContext flowContext){
        String deployName = flowContext.checkData("deployName", String.class);
        JSONObject contextData = flowContext.checkData("contextData", JSONObject.class);
        QuickWorkFlow quickWorkFlow = flowContext.checkInstanceData(QuickWorkFlow.class);

        StartWorkFlowRequest startWorkFlowRequest = new StartWorkFlowRequest();
        startWorkFlowRequest.definitionName = deployName;
        startWorkFlowRequest.initiator = "张三";
        startWorkFlowRequest.contextData.putAll(contextData);
        flowContext.putInstanceData(startWorkFlowRequest, FlowContextDataRange.ContextThreadLocal);

        WorkFlowInstance workFlowInstance = quickWorkFlow.startWorkFlow(startWorkFlowRequest);
        flowContext.putCurrentFlowData("workFlowInstanceId", workFlowInstance.getId());

        flowContext.startFlow(new PrintWorkFlowInstanceHistoryFlow())
                .putCurrentCompositeFlowInstanceData(workFlowInstance)
                .execute();
    }

    private void checkStatus(FlowContext flowContext){
        WorkFlowInstanceStatus workFlowInstanceStatus = flowContext.checkInstanceData(WorkFlowInstanceStatus.class);
        Long workFlowInstanceId = flowContext.checkData("workFlowInstanceId", Long.class);
        QuickWorkFlow quickWorkFlow = flowContext.checkInstanceData(QuickWorkFlow.class);

        WorkFlowInstance workFlowInstance = quickWorkFlow.getSingleWorkFlowInstance(workFlowInstanceId);
        CheckInstance.newCheck().fieldValueCheck(workFlowInstance.getStatus(), workFlowInstanceStatus.status, "实例状态");
    }
}
